import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/image_network_widget.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/double_extension.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:jetour_line/utils/permission_utils.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../base_widget/my_alert.dart';
import '../../models/jetour_line_detail.dart';
import '../../network/jetour_http.dart';

typedef _DelNodeCallBack = void Function();

class EditNodeScreen extends StatefulWidget {
  late final Node? nodeInfo;
  final int nodeId;
  final int id;
  final _DelNodeCallBack callBack;

  EditNodeScreen(
      {Key? key,
      this.nodeInfo,
      required this.id,
      required this.nodeId,
      required this.callBack})
      : super(key: key);

  @override
  State<EditNodeScreen> createState() => _EditNodeScreenState();
}

class _EditNodeScreenState extends State<EditNodeScreen> {
  String? description;
  List images = [];
  final int maxImage = 15;
  final ScrollController _scrollController =
      ScrollController(); //创建一个ScrollController
  bool isUpIng = false;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.nodeInfo == null) {
      getDetail();
    }
  }

  void getDetail() {
    Map<String, dynamic> map = Map();
    map['id'] = widget.id;
    JetourHttp()
        .get(JetourRouter.GuideToolNodeDetail, params: map)
        .then((value) {
      widget.nodeInfo = Node.fromJson(value);
      setState(() {});
    });
  }

  String? oldText;
  bool isFirst = true;

  @override
  Widget build(BuildContext context) {
    if (isFirst && widget.nodeInfo != null) {
      int len = widget.nodeInfo!.images.length;
      for (int i = 0; i < (len < 6 ? len : 6); i++) {
        images.add(widget.nodeInfo!.images[i]);
      }
      description = widget.nodeInfo!.description;
      isFirst = false;
    }
    return GestureDetector(
      onTap: (){
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        color: Colors.transparent,
        child: Stack(
          children: [
            BaseScaffold(
                backgroundColor: MyColors.white,
                title: '编辑',
                body: Column(children: [
                  Expanded(
                    child: ListView(
                      children: [imgWidget(), desWidget(), ],
                    ),
                  ),
                  bottomWidget()
                ],
                )),
            if(isUpIng)
              Container(
                color: Colors.black26,
                width: double.infinity,
                height: double.infinity,
                child:  Center(
                  child: CircularProgressIndicator(
                    backgroundColor: Colors.white,
                    strokeWidth: 4.0,
                    valueColor: AlwaysStoppedAnimation<Color>(MyColors.appColor),
                  ),
                ),
              )
          ],
        ),
      ),
    );
  }

  Widget imgWidget() {

    int index = images.length;
    index  = index~/4 ;
    return Container(
      width: double.infinity,
      height: 250.px+200.px*index,
      padding: EdgeInsets.only(left: 32.px, top: 32.px, bottom: 32.px),
      color: MyColors.white,
      child: GridView.extent(
        physics: const NeverScrollableScrollPhysics(),
        //次轴的宽度
        maxCrossAxisExtent: 170.px,
        //次轴的宽度
        //上下左右的内边距
        mainAxisSpacing: 4.0,
        //主轴元素间距
        crossAxisSpacing: 4.0,
        //次轴元素间距
        padding: EdgeInsets.all(4.0),
        children: [
          for (int i = 0; i < images.length + 1; i++) imageItemWidget(i),
        ], //添加
      ),

      // ListView(
      //   controller: _scrollController,
      //   scrollDirection: Axis.horizontal,
      //   children: [
      //     for (int i = 0;
      //         i < (images.length < 6 ? (images.length + 1) : images.length);
      //         i++)
      //       imageItemWidget(i),
      //   ],
      // ),
    );
  }

  Widget imageItemWidget(int index) {
    bool isAdd = index == images.length;
    String? image;
    File? imageFile;
    if (images.isNotEmpty && index < images.length) {
      if (images[index].runtimeType == String) {
        image = images[index];
      } else {
        imageFile = images[index];
      }
    }
    return GestureDetector(
      onTap: () {
        if (isAdd) {
          if (images.length == maxImage) {
            AhaUtils.showTxt('最多选择$maxImage张图片');
          } else {
            selectAssets();
          }
        }
      },
      child: Padding(
        padding: EdgeInsets.only(right: 20.px),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(4.px)),
          child: Container(
              color: MyColors.colorF1F1F1,
              width: 200.px,
              height: 200.px,
              alignment: Alignment.center,
              child: isAdd
                  ? BaseImage(
                      image: 'lsgj_btn_add',
                      width: 60.px,
                      height: 60.px,
                    )
                  : Stack(
                      children: [
                        Container(
                            child: image == null
                                ? Image.file(
                                    imageFile!,
                                    fit: BoxFit.cover,
                                    width: 200.px,
                                    height: 200.px,
                                  )
                                : ImageNetworkWidget(
                                    image,
                                    width: 200.px,
                                    height: 200.px,
                                  )),
                        Positioned(
                            right: 0,
                            top: 0,
                            child: ClipRRect(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(30.px)),
                              child: Container(
                                width: 60.px,
                                height: 60.px,
                                color: Colors.black54,
                              ),
                            )),
                        Positioned(
                            top: 0.px,
                            right: 0.px,
                            child: GestureDetector(
                                onTap: () {
                                  images.removeAt(index);
                                  setState(() {});
                                },
                                child: Container(
                                  color: Colors.transparent,
                                  padding:
                                      EdgeInsets.only(right: 15.px, top: 15.px),
                                  alignment: Alignment.topRight,
                                  width: 56.px,
                                  height: 60.px,
                                  child: BaseImage(
                                    image: 'lsgj_btn_closewh',
                                    width: 30.px,
                                    height: 30.px,
                                  ),
                                )))
                      ],
                    )),
        ),
      ),
    );
  }

  Future<void> selectAssets() async {
    PermissionUtils.requestPhotoPickPermission(context, (bool isAgree) async {
      if(isAgree){
        final List<AssetEntity>? result = await AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
              maxAssets: maxImage - images.length, requestType: RequestType(1)),
        );
        for (int i = 0; i < result!.length; i++) {
          File imageFile = await result[i].file as File;
          images.add(imageFile);
        }
        _scrollController.animateTo(images.length * 200.px,
            duration: Duration(milliseconds: 50), curve: Curves.ease);
        setState(() {});
      }
    });

  }

  Widget desWidget() {
    return Padding(
      padding: EdgeInsets.only(left: 32.px, right: 32.px),
      child: Column(
        children: [
          SizedBox(
            width: double.infinity,
            height: 280.px,
            child: TextField(
                onChanged: (value) {
                  description = value;
                },
                maxLength: 150,
                maxLines: 6,
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: description ?? "", //判断keyword是否为空
                    // 保持光标在最后
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: '$description'.length)))),
                decoration: const InputDecoration(
                  hintText: '填写行程描述',
                  border: InputBorder.none,
                  counterText: '',
                  focusedBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  errorBorder: InputBorder.none,
                  disabledBorder: InputBorder.none,
                ),
                style: TextStyle(fontSize: 28.px, color: MyColors.color333333)),
          ),
          Container(
            width: double.infinity,
            height: 1.px,
            color: MyColors.colorF1F1F1,
          )
        ],
      ),
    );
  }

  Widget bottomWidget() {
    return Padding(
      padding: EdgeInsets.all(32.px),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(40.px)),
            child: GestureDetector(
              onTap: () {
                delNode();
              },
              child: Container(
                alignment: Alignment.center,
                width: 170.px,
                height: 80.px,
                color: MyColors.colorF1F1F1,
                child: Text(
                  '删除',
                  style:
                      TextStyle(fontSize: 30.px, color: MyColors.color999999),
                ),
              ),
            ),
          ),
          SizedBox(
            width: 32.px,
          ),
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(40.px)),
              child: GestureDetector(
                onTap: () {
                  saveTravel();
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 80.px,
                  color: MyColors.color00A198,
                  child: Text(
                    '保存',
                    style: TextStyle(fontSize: 30.px, color: MyColors.white),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Future<void> saveTravel() async {
    print('saveTravel1');
    String? msg;
    if (images.isEmpty) {
      msg = '请选择照片';
    } else if (description == null) {
      msg = '请输入行程描述';
    }
    if (msg != null) {
      AhaUtils.showTxt(msg);
    } else {
      isUpIng = true;
      setState(() {

      });
      List<String> imageUrls = await JetourHttp().upImages(images);
      if (widget.nodeInfo!.images.length > 6) {
        for (int i = 6; i < widget.nodeInfo!.images.length; i++) {
          imageUrls.add(widget.nodeInfo!.images[i]);
        }
      }
      Map<String, dynamic> map = {};
      map['id'] = widget.nodeInfo?.nodeId;
      map['description'] = description;
      map['images'] = imageUrls;

      JetourHttp()
          .post(JetourRouter.GuideToolSaveNodeDetail, data: map)
          .then((value) {
        isUpIng = false;
        setState(() {

        });
        if (value == null) {
          return;
        }
        widget.nodeInfo?.images = imageUrls;
        widget.nodeInfo?.description = description!;
        Navigator.pop(context, widget.nodeInfo);
      });
    }
  }

  void delNode() {
    showMyDialog(context, '是否删除该行程点', "是", "否", (index) {
      if (index == 0) {
        int nodeId = widget.nodeInfo!.nodeId;
        Map<String, dynamic> map = Map();
        map['id'] = widget.id;
        map['nodeId'] = nodeId;
        JetourHttp()
            .post(JetourRouter.GuideToolDeletNode, data: map)
            .then((value) {
          Navigator.pop(context);
          widget.callBack();
        });
      }
    });
  }
}
